const STORAGE_KEY = 'outpatientBills'

export function loadBills() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY)
    return raw ? JSON.parse(raw) : []
  } catch (_) {
    return []
  }
}

export function saveBills(bills) {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(bills || []))
  } catch (_) {}
}

export function addBill(bill) {
  if (!bill) return
  const existing = loadBills()
  const merged = [bill, ...existing.filter(b => b.id !== bill.id)]
  saveBills(merged)
  return merged
}

export function updateBillStatus(id, status) {
  const arr = loadBills().map(b => (b.id === id ? { ...b, status } : b))
  saveBills(arr)
  return arr
}

export function clearAllBills() {
  saveBills([])
}

export default { loadBills, saveBills, addBill, updateBillStatus, clearAllBills }


